from django.shortcuts import render

from django.http import HttpResponse
from repitle import models
from repitle.repitleapp import t1,kongke
from django.http import StreamingHttpResponse
import json
import os
from django.conf import settings

name=None
comments=None

def index(request):
    return render(request,'home/index.html')

def movieindex(request):
    return render(request,'douban/index.html')
    
def moviesearch(request):
    global name
    global comments
    try:
        geturl = request.POST['URL']
        name = geturl.split('/')[-2]
        print(geturl)
        comments =t1.main(geturl)
        #print(comments)
        context = {'commentslist':comments[0]}
    except:
        return HttpResponse("出错了")
    return render(request,"douban/info.html",context)

def download(request):
    savename = name+'.txt'
    savepath = 'repitlesave/douban/'+savename
    with open(savepath,'w',encoding='utf-8') as f:
        for i in comments:
            for j in i:
                f.write(j)
    file=open(savepath,'r',encoding='utf-8')
    response =StreamingHttpResponse(file)
    response['Content-Type']='application/octet-stream'
    response['Content-Disposition']='attachment;filename={}'.format(savename)
    return response

def searchroomindex(request):
    return render(request,'searchroom/index.html')

def serachroom(request):
    try:
        f = open(os.path.join(settings.BASE_DIR, 'final.json'),'r',encoding='utf-8')
        #f = open('repitle\repitleapp\result.json', )
        fdic = json.load(f)
        #print(info_data)
        building = request.POST.get("building")+'-'
        day = int(request.POST.get("day"))
        time=int(request.POST.get("time"))
        week=int(request.POST.get("week"))
        res=[]
        for name,course in fdic.items():
            if building in name:
                if course[day][time][week]==0:
                    res.append(name)
        
        context = {'course':res}
    except:
        return HttpResponse("soory")
    return render(request,"searchroom/info.html",context)
